package com.amoyt.project.service.security.impl;

import com.amoyt.project.domain.pojo.Role;
import com.amoyt.project.domain.pojo.User;
import com.amoyt.project.domain.bo.LoginUser;
import com.amoyt.project.mapper.MenuMapper;
import com.amoyt.project.mapper.RoleMapper;
import com.amoyt.project.mapper.UserMapper;
import com.amoyt.project.service.security.MenuService;
import com.amoyt.project.service.security.RoleService;
import com.amoyt.project.service.security.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 用户详情实现类，除此之外，无其他作用
 *
 * @author xiaotang
 * @date 2020/05/05
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    /**
     * 根据用户名查询用户信息 [Security框架指定]
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询用户
        User user = userService.queryUserByUserName(username);

        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 2. 查询用户拥有的权限
        List<String> permissions = this.getPermissionsByUserId(user.getUserId());

        return new LoginUser(user, permissions);
    }

    /**
     * 功能方法：根据用户ID查询权限标识 列表,角色等
     * @param userId
     * @return
     */
    private List<String> getPermissionsByUserId(String userId) {

        // 2.1 查询角色标识（如 admin、super_admin）
        List<String> roleCodes = roleService.getRoleKeyByUserId(userId);

        // 2.2 查询菜单权限标识（如 user:add、user:delete）
        List<String> menuPerms = menuService.getMenuPermsByUserId(userId);

        // 2.3 合并角色和菜单权限（角色标识需加前缀 ROLE_，符合 Security 规范）
        List<String> permissions = new ArrayList<>();

        // 2.3.1 添加角色权限（格式：ROLE_角色编码）
        if (roleCodes != null) {
            roleCodes.forEach(roleCode -> permissions.add("ROLE_" + roleCode));
        }

        // 2.3.2 添加菜单权限
        if (menuPerms != null) {
            permissions.addAll(menuPerms);
        }

        return permissions;
    }

}